<script>
import Vue from 'vue'
import TencentCloudChat from '@tencentcloud/chat';
import TIMUploadPlugin from 'tim-upload-plugin';
import TIMProfanityFilterPlugin from 'tim-profanity-filter-plugin';


// #ifdef APP-PLUS
const TUICallKit = uni.requireNativePlugin('TencentCloud-TUICallKit'); //【1】引入 TUICallKit 插件
TUICallKit.enableFloatWindow(true);
Vue.prototype.$TUICallKit = TUICallKit;
import { genTestUserSig } from './common/js/TUICallKit/GenerateTestUserSig.js'
// #endif


export default {
    onLaunch: async function (data) {
        // console.log(data);
        // this.$comFun.clearUserInfo();

        // 大逃杀game相关---start
        this.getNavH();
        // 大逃杀game相关---end

        // #ifdef H5
        if (data.path == undefined) {
            if (process.env.NODE_ENV == 'development') {
                uni.switchTab({
                    url: '/'
                });
            } else {
                uni.redirectTo({
                    url: '/'
                });
            }
        }
        this.$store.dispatch('setDeviceType', 'h5');
        // #endif

        // #ifdef APP-PLUS
        const that = this;
        uni.getSystemInfo({
            success: function (res) {
                // 客户端平台，值域为：ios、android  
                // console.log(res);
                that.$store.dispatch('setDeviceType', res.platform);
            }
        });
        // #endif

        let hideTabbarBool = false;
        let hideTabbarTime = setInterval(() => {
            if (hideTabbarBool) {
                clearInterval(hideTabbarTime);
            } else {
                uni.hideTabBar({
                    complete: ((res) => {
                        // console.log(res);
                        if (res.errMsg == "hideTabBar:ok") {
                            hideTabbarBool = true;
                        }
                    })
                });
            }
        }, 100);
        console.log('App Launch')
    },
    onShow: function () {
        uni.hideTabBar();
        console.log('App Show');
    },
    onHide: function () {
        console.log('App Hide')
    },
    methods: {
        getNavH() {
            // 获取导航高度；
            uni.getSystemInfo({
                success: res => {
                    let NavHeight = res.statusBarHeight;
                    this.$gameStore.NavHeight = NavHeight
                    this.$gameStore.safe_top = res.safeArea.top
                },
                fail(err) {
                    console.log(err);
                }
            })
        },
        //上传图片 count-选择图片数量
        async imgUpload(count, callback) {
            const that = this;
            uni.chooseImage({
                count: count, //默认9
                sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
                sourceType: ['album', 'camera '], //从相册选择
                success: async function (chooseImageRes) {
                    // console.log(JSON.stringify(chooseImageRes.tempFilePaths));
                    const tempFilePaths = chooseImageRes.tempFilePaths;
                    // console.log(tempFilePaths);
                    that.$comFun.openLoading();
                    let img_list = [];
                    for (var i = 0; i < tempFilePaths.length; i++) {
                        let res = await that.$request.uploadFile(tempFilePaths[i]);
                        // console.log(res);
                        if (res.code == 200) {
                            img_list.push(res.result);
                        }
                    }
                    that.$comFun.closeLoading();
                    callback(img_list);
                },
            });
        },
        //上传图片-会返回图片信息 count-选择图片数量
        async imgUploadHasInfo(count, callback) {
            const that = this;
            uni.chooseImage({
                count: count, //默认9
                sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
                sourceType: ['album', 'camera '], //从相册选择
                success: async function (chooseImageRes) {
                    // console.log(JSON.stringify(chooseImageRes.tempFilePaths));
                    const tempFilePaths = chooseImageRes.tempFilePaths;
                    // console.log(tempFilePaths);
                    that.$comFun.openLoading();
                    let img_list = [];
                    for (var i = 0; i < tempFilePaths.length; i++) {
                        let res = await that.$request.uploadFileHasInfo(tempFilePaths[i]);
                        // console.log(res);
                        if (res.code == 200) {
                            img_list.push(res.result);
                        }
                    }
                    that.$comFun.closeLoading();
                    callback(img_list);
                },
            });
        },
        async initAppUpdate() {
            const that = this;
            const res = await this.$request.get('public/getAppVersion', {});
            // console.log(res);
            // console.log(plus.runtime);
            if (res.code == 200) {
                plus.runtime.getProperty(plus.runtime.appid, function (wgtinfo) {
                    // console.log(wgtinfo.versionCode);
                    const versionCode = wgtinfo.versionCode;
                    // const versionCode = 100;
                    // this.runtime = plus.runtime.versionCode + ',' + res.result.versionCode + ',' + (Number(res.result.versionCode) > Number(versionCode));
                    // console.log(this.runtime);
                    if (Number(res.result.versionCode) > Number(versionCode)) {
                        if (that.$store.state.deviceType == 'android') {
                            that.$store.dispatch('setAppUpdate', res.result.update_android_url)
                        } else if (that.$store.state.deviceType == 'ios') {
                            that.$store.dispatch('setAppUpdate', res.result.ios_url)
                        }
                    } else {
                        that.$store.dispatch('setAppUpdate', false)
                    }
                });
            }
        },
        async getConfigList() {
            // let data = {
            //     GIVE_PRO: 'givePro',
            //     EXCHANGE_GOODS_I_PRO: 'exchangeGoodsIPro',
            //     IS_JD_GAME: 'isJdGame',
            //     CARD_MAX_NUM: 'cardMaxNum',
            //     ANDROID_URL: 'androidUrl',
            //     COM_STORE_CARD_PRO: 'comStoreCardPro',
            //     ONE_STORE_PLEDGE: 'oneStorePledge',
            //     TWO_STORE_PLEDGE: 'twoStorePledge',
            //     THREE_STORE_PLEDGE: 'threeStorePledge',
            // }
            if (this.$store.state.configList == '') {
                const res = await this.$request.get('public/getConfigList', {});
                if (res.code == 200) {
                    this.$store.dispatch('setConfigList', res.result);
                    return res.result;
                } else {
                    return '';
                }
            } else {
                return this.$store.state.configList;
            }
        },
        async initChat(callback) {
            const userInfo = this.$comFun.getUserInfo();
            console.log("userInfo:", userInfo);
            if (userInfo == '') {
                callback(false)
                return;
            }
            const that = this;
            let options = {
                SDKAppID: 1600021127 // 接入时需要将0替换为您的即时通信 IM 应用的 SDKAppID
            };
            // 创建 SDK 实例，`TencentCloudChat.create()`方法对于同一个 `SDKAppID` 只会返回同一份实例
            let chat = TencentCloudChat.create(options); // SDK 实例通常用 chat 表示
            chat.setLogLevel(1); // 普通级别，日志量较多，接入时建议使用
            // chat.setLogLevel(1); // release 级别，SDK 输出关键信息，生产环境时建议使用
            // 注册腾讯云即时通信 IM 上传插件
            chat.registerPlugin({ 'tim-upload-plugin': TIMUploadPlugin });
            // 注册腾讯云即时通信 IM 本地审核插件
            chat.registerPlugin({ 'tim-profanity-filter-plugin': TIMProfanityFilterPlugin });

            const res = await this.$request.get('user/getImSign', {});
            console.log("chat-getImSign", res);
            if (res.code == 200) {
                let promise_login = chat.login({
                    userSig: res.result,
                    userID: userInfo.userId,
                })
                // console.log("promise_login,", promise_login);
                promise_login.then(function (imResponse) {
                    console.log("chat-login", imResponse.data); // 登录成功



                    // #ifdef APP-PLUS
                    // 腾讯音视频登录
                    const { userSig, sdkAppID: SDKAppID } = genTestUserSig(userInfo.userId); // 控制台生成 userSig
                    const loginParams = { SDKAppID, userID: userInfo.userId, userSig };   // 使用 SDKAppID、userSig
                    //【2】登录 TUICallKit 组件
                    that.$TUICallKit.login(loginParams, res => {
                        if (res.code === 0) {
                            console.log('[TUICallKit] login success.');
                        } else {
                            console.error('[TUICallKit] login failed, failed message = ', res.msg, params);
                        }
                    });
                    // #endif




                    let onSdkReady = function (event) {
                        console.log("chat-onSdkReady", event);
                        Vue.prototype.$txChat = chat;
                        Vue.prototype.$TencentCloudChat = TencentCloudChat;
                        callback(true)
                    };
                    chat.on(TencentCloudChat.EVENT.SDK_READY, onSdkReady);
                    let onSdkNotReady = function (event) {
                        console.log("chat-onSdkNotReady", event);
                        callback(false)
                    };
                    chat.on(TencentCloudChat.EVENT.SDK_NOT_READY, onSdkNotReady);
                }).catch(function (imError) {
                    console.warn('login error:', imError); // 登录失败的相关信息
                    callback(false)
                });
            } else {
                that.$comFun.toast('chat-获取聊天凭证失败，请稍后再试');
            }
        }
    }
}
</script>

<style lang="scss">
/*每个页面公共css */
@import "@/common/css/public.scss";
@import "@/common/css/iconfont_base/iconfont.css";
@import "@/common/css/iconfont_app/iconfont.css";
</style>
